package top.jingles.sayhiintime;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.File;
import java.util.Random;

public class SayHiInTimeActivity
        extends Activity {
    private String bgPicPath = "";
    private Button btnStartService;
    private Button btnStopService;
    private Button[] btnTimePreview = new Button[18];
    private LinearLayout mainLayout;
    public int screenHeight;
    public int screenWidth;
    private Spinner spinnerVoiceStyle;
    private ProgressBar splitLine;

    private void showToast(String msg) {
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
    }

    private void debugPrint(String msg) {
        showToast(msg);
    }

    private String getBgPicPath() {
        if (this.bgPicPath.length() == 0) {
            this.bgPicPath = (Environment.getExternalStorageDirectory().getPath() + Setting.getInstance().getBgpicPath());
        }
        return this.bgPicPath;
    }

    private void initControls() {
        this.mainLayout = (findViewById(R.id.mainLayout));
        this.btnStartService = (findViewById(R.id.btnStartService));
        this.btnStopService = (findViewById(R.id.btnStopService));
        this.splitLine = (findViewById(R.id.splitLine));
        this.spinnerVoiceStyle = (findViewById(R.id.spinnerVoiceStyle));
        this.btnTimePreview[0] = (findViewById(R.id.btnTime6));
        this.btnTimePreview[1] = (findViewById(R.id.btnTime7));
        this.btnTimePreview[2] = (findViewById(R.id.btnTime8));
        this.btnTimePreview[3] = (findViewById(R.id.btnTime9));
        this.btnTimePreview[4] = (findViewById(R.id.btnTime10));
        this.btnTimePreview[5] = (findViewById(R.id.btnTime11));
        this.btnTimePreview[6] = (findViewById(R.id.btnTime12));
        this.btnTimePreview[7] = (findViewById(R.id.btnTime1p));
        this.btnTimePreview[8] = (findViewById(R.id.btnTime2p));
        this.btnTimePreview[9] = (findViewById(R.id.btnTime3p));
        this.btnTimePreview[10] = (findViewById(R.id.btnTime4p));
        this.btnTimePreview[11] = (findViewById(R.id.btnTime5p));
        this.btnTimePreview[12] = (findViewById(R.id.btnTime6p));
        this.btnTimePreview[13] = (findViewById(R.id.btnTime7p));
        this.btnTimePreview[14] = (findViewById(R.id.btnTime8p));
        this.btnTimePreview[15] = (findViewById(R.id.btnTime9p));
        this.btnTimePreview[16] = (findViewById(R.id.btnTime10p));
        this.btnTimePreview[17] = (findViewById(R.id.btnTime11p));
    }

    private void initScreenInfo() {
        requestWindowFeature(1);
        DisplayMetrics localDisplayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(localDisplayMetrics);
        this.screenHeight = localDisplayMetrics.heightPixels;
        this.screenWidth = localDisplayMetrics.widthPixels;
    }

    private void setBackground() {
        try {
            String picPathStr = getBgPicPath();
//            debugPrint(picPathStr);
            File picPath = new File(picPathStr);
            if ((picPath.exists()) && (picPath.isDirectory()) && (picPath.canRead())) {
                String[] files = picPath.list();
                int fileCount = 0;
                if (files != null) {
                    fileCount = files.length;
                }
                if (fileCount == 0) {
                    return;
                }
                setBackground(new Random().nextInt(fileCount) + 1);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void setBackground(int fileId) {
        String[] files;
        try {
            File picPath = new File(getBgPicPath());
            if ((!picPath.exists()) || (!picPath.isDirectory()) || (!picPath.canRead())) {
                return;
            }
            files = picPath.list();
            if (files.length == 0) {
                return;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return;
        }

        if (files == null) {
            return;
        }

        if (fileId > files.length) {
            fileId = files.length;
        }
        Bitmap bitmap = BitmapFactory.decodeFile(getBgPicPath() + "/" + files[(fileId - 1)]);
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float f1 = width / height;  // 图片的宽高比
        float f2 = this.screenWidth / this.screenHeight;    // 屏幕的宽高比

        int newWidth;
        int newHeight;
        if ((f1 >= f2) && (width >= this.screenWidth)) {
            newWidth = this.screenWidth;
            newHeight = (int) (newWidth / f1);
        } else if ((f1 < f2) && (height >= this.screenHeight)) {
            newHeight = this.screenHeight;
            newWidth = (int) (newHeight * f1);
        } else {
            newHeight = height;
            newWidth = width;
        }
//        debugPrint("PictureSize:"+newWidth+","+newHeight);
        Bitmap newBitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
        BitmapDrawable drawable = new BitmapDrawable(getResources(), newBitmap);
        drawable.setTileModeXY(Shader.TileMode.MIRROR, Shader.TileMode.MIRROR);
        this.mainLayout.setBackgroundDrawable(drawable);
    }

    private void getStoragePower() {
        int permission_write = ContextCompat.checkSelfPermission(SayHiInTimeActivity.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        int permission_read = ContextCompat.checkSelfPermission(SayHiInTimeActivity.this,
                Manifest.permission.READ_EXTERNAL_STORAGE);
        if (permission_write != PackageManager.PERMISSION_GRANTED
                || permission_read != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "正在请求权限", Toast.LENGTH_SHORT).show();
            //申请权限，特征码自定义为1，可在回调时进行相关判断
            ActivityCompat.requestPermissions(SayHiInTimeActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //权限已成功申请
                    setBackground();
                } else {
                    //用户拒绝授权
                    Toast.makeText(this, "无法获取SD卡读写权限", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        initScreenInfo();
        setContentView(R.layout.activity_main);
        initControls();
        this.btnStartService.setOnClickListener(new ButtonOnClickListener());
        this.btnStopService.setOnClickListener(new ButtonOnClickListener());
        this.spinnerVoiceStyle.setOnItemSelectedListener(new SpinnerOnItemSelectedListener());
        this.splitLine.getProgressDrawable().setAlpha(64);
        this.btnStartService.getBackground().setAlpha(128);
        this.btnStopService.getBackground().setAlpha(128);
        this.spinnerVoiceStyle.getBackground().setAlpha(128);
        for (int i = 0; i < 18; i++) {
            this.btnTimePreview[i].setOnClickListener(new ButtonOnClickListener());
            this.btnTimePreview[i].getBackground().setAlpha(64);
        }
        try {
            stopService(new Intent(this, CheckTimeService.class));
            this.btnStartService.setEnabled(false);
            this.btnStopService.setEnabled(true);
            startService(new Intent(this, CheckTimeService.class));
            showToast("整点报时已自动开启");
            // android8.0后，需要动态申请权限
            getStoragePower();
            setBackground();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    protected void onDestroy() {
        CheckTimeListener.ResReset();
        super.onDestroy();
    }

    private class ButtonOnClickListener
            implements OnClickListener {
        private ButtonOnClickListener() {
        }

        public void onClick(View thisView) {
            if (thisView.getId() == R.id.btnStartService) {
                SayHiInTimeActivity.this.btnStartService.setEnabled(false);
                SayHiInTimeActivity.this.btnStopService.setEnabled(true);
                SayHiInTimeActivity.this.startService(new Intent(SayHiInTimeActivity.this, CheckTimeService.class));
                SayHiInTimeActivity.this.showToast("整点报时已开启，可后台运行");
                return;
            } else if (thisView.getId() == R.id.btnStopService) {
                SayHiInTimeActivity.this.btnStopService.setEnabled(false);
                SayHiInTimeActivity.this.btnStartService.setEnabled(true);
                SayHiInTimeActivity.this.stopService(new Intent(SayHiInTimeActivity.this, CheckTimeService.class));
                SayHiInTimeActivity.this.showToast("整点报时已关闭");
                return;
            }

//            debugPrint("this is a debug");
            String buttonText = ((Button) thisView).getText().toString();
//            debugPrint("当前点击按钮："+buttonText);
            buttonText = buttonText.replaceAll("点", "")
                    .replaceAll("早上", "")
                    .replaceAll("上午", "")
                    .replaceAll("午间", "")
                    .replaceAll("傍晚", "下午")
                    .replaceAll("晚上", "下午")
                    .replaceAll("深夜", "下午");
            int hour;
            if (!buttonText.contains("下午")) {
                hour = Integer.parseInt(buttonText);
            } else {
                buttonText = buttonText.replaceAll("下午", "");
                hour = Integer.parseInt(buttonText) + 12;
            }

//            debugPrint("当前点击小时："+hour);
            CheckTimeListener.trySpeak(hour);

//            try {
//                System.loadLibrary("Aisound");
//                debugPrint("load library ok: Aisound");
//            } catch (UnsatisfiedLinkError error) {
//                debugPrint("load library error: " + error.getMessage());
//            }
        }
    }

    private class SpinnerOnItemSelectedListener
            implements OnItemSelectedListener {
        private SpinnerOnItemSelectedListener() {
        }

        public void onItemSelected(AdapterView<?> adapterView, View view, int itemIndex, long paramLong) {
            String str = adapterView.getItemAtPosition(itemIndex).toString();
            Setting.getInstance().setVoiceStyle(str);
        }

        public void onNothingSelected(AdapterView<?> paramAdapterView) {
        }
    }
}
